package sitar;
import flash.events.Event;
import flash.filesystem.File;
import oboe.core.SigSlot;
import sitar.ui.Selector;

/**
 * ...
 * @author Felipe Manga
 */

class NewProjectWizard extends SigSlot
{
	var projectDir:File;
	
	public function new( dir ) 
	{
		super();
		projectDir = dir;
	}
	
	@slot function onAddToParent():Void
	{
		var template = File.applicationDirectory.resolvePath("templates");
		var templates:Array< Array< Dynamic > > = [];
		var listing = template.getDirectoryListing();
		
		for ( pos in 0 ... listing.length )
		{
			if ( listing[pos].name.charAt(0) == "." ) continue;
			templates.push( [listing[pos].name, listing[pos]] );
		}
		this.addChild( new Selector("onPickTemplate", templates) );
	}
	
	@slot function onPickTemplate( template:File ):Void
	{
		this.signalUp("log", ["Initializing", template.name, "project \"", projectDir.name, "\"..."]);
		
		template.addEventListener( Event.COMPLETE, onComplete );
		// template.copyToAsync( projectDir, true );
		copyTo( template, projectDir );
		onComplete( null );
	}
	
	function copyTo( src:File, dest:File ):Void
	{
		if ( src.name.charAt(0) == "." ) return;
		if ( src.isDirectory )
		{
			var list = src.getDirectoryListing();
			for ( file in list )
			{
				if ( file.name.charAt(0) == "." ) continue;
				var res = dest.resolvePath( dest.nativePath + "/" + file.name );
				if( file.isDirectory ) res.createDirectory();
				copyTo( file, res );
			}
		}
		else
		{
			src.copyTo( dest, true );
		}
	}
	
	function onComplete( e:Event ):Void
	{
		this.signalUp("newProjectDone", [ this.projectDir ]);
		this.selfDestruct();
	}	
}